import React,{Component} from 'react';
import { Form, Input, Button, Radio, Select, message } from 'antd';
import { Link, history} from 'react-router-dom';
import './index.less';
import axios from 'axios';
import {connect} from 'react-redux';
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
const { TextArea } = Input;
const RadioGroup = Radio.Group;
const FormItem = Form.Item;
const Option = Select.Option;

class createcertificate extends React.Component {
	constructor(props){
		super(props)
		this.state = {
			value: 1,
			englishName: '',
			caType: '',
			orgList: [],
			defaultValue: '',
			id: '',
		}
	}


	handleSubmit = (e)=>{
		e.preventDefault();
		const _this = this;
		const Token = localStorage.getItem("token");
		const type = (this.state.value == 2) ? this.state.caType : this.state.value;
		const userName = this.state.userName;
		const userPwd = this.state.userPwd;
		const englishName = this.state.englishName;
		const sessionValue = this.state.defaultValue;
		this.props.form.validateFields((err, values) => {
			if(!err){
				var data = {
						type: type,
						userName: userName,
						userPwd: userPwd,
						userAffiliation: englishName,
						userOrg: englishName,
						roleType: '',
						publicKey: sessionValue,
						caOrg: '',
						caId: values.caId,
						secretName: this.props.secretName,
					}
				// console.log(data);
				axios({
					method: 'post',
					url: '/api/block/baas/Ca/verifyCertId?certId=' + values.caId + '&orgId='+ this.props.changeOrgid,
				    headers: {
				      'Content-Type': 'application/json',
				      Authorization:Token,
					}
				})
				.then(function(response){
					// console.log(response);
					if(response.data.message == '证书ID重复，请重新输入'){
						message.warning('证书ID重复，请重新输入');
						return false;
					}else{
						if(type == ''){
							message.warning("请选择证书！");
							return false
						}else{
							axios({
								method: 'post',
								url: '/api/block/baas/Ca/enroll',
								data: data,
							    headers: {
							      'Content-Type': 'application/json',
							      Authorization:Token,
								}
							})
							.then(function(response){
								// console.log(response);
								if(response.data.message == "生成证书失败!"){
									message.error("生成证书失败！");
								}else if(response.data.message == '生成证书成功!') {
									message.success('生成证书成功!');
									// console.log(response);
									_this.setState({
										id: response.data.data.id,
									})
									setTimeout(()=>{
										_this.props.dispatch({
											type: 'id',
											Id: _this.state.id
										})
										_this.props.history.push('/certificateManagement/downloadCertificate');
									},2000);
								}
							})
							.catch(function(error){
								console.log(error)
							})
						}
					}
				})
				.catch(function(error){
					message.error('提交失败');
				})
			}else {
				console.log('Received values of form: ', values);
			}
		})
	}


	onChangeRadio = (e) => {
	    // console.log('radio checked', e.target.value);
	    this.setState({
	      value: e.target.value,
	    });
	    const Token = localStorage.getItem("token");
	    if(e.target.value == 2){
	    	axios({
	    		method: 'post',
	    		url: '/api/block/baas/Ca/getCaOrgList',
    		    headers: {
    		      'Content-Type': 'application/json',
    		      Authorization:Token,
    			}
	    	})
	    	.then((response)=>{
    			this.setState({
    				orgList: response.data,
    			})
	    	})
	    	.catch((error)=>{
	    		console.log(error)
	    	})
	    }
	}

	handleChange = (value)=> {
	   console.log(`selected ${value}`);
	   this.setState({
	   		caType: value
	   })
	} 

	getOrgEnglishName =()=>{
		// setTimeout(()=>{
			// console.log(this.props)
		// })
		setTimeout(()=>{
			this.props.changeOrgid;
			this.props.secretName
			if(this.props.changeOrgEnglishName){
				this.setState({
					englishName: this.props.changeOrgEnglishName.english_name,
				})
			}
		})
	}

	componentWillUpdate(nextProps) {
		if(nextProps.changeOrgid != this.props.changeOrgid){
			this.getOrgEnglishName();
		}
	}

	componentWillMount(){
		this.getOrgEnglishName();
		sessionStorage.setItem("defaultValue",this.props.PublicKey);
		this.setState({
			defaultValue: sessionStorage.getItem("defaultValue"),
		})
		const _this = this;
		const Token = localStorage.getItem("token");
		axios({
			method: 'get',
			url: '/api/block/baas/Ca/getUser',
            headers: {
              'Content-Type': 'application/json',
              Authorization:Token,
        	}
		})
		.then(function(response){
			// console.log(response)
			_this.setState({
				userName: response.data.username,
				userPwd: response.data.password,
			})
		})
		.catch(function(error){
			message.warning('请求失败，请刷新重试！')
		})
	}

	render(){
		const { getFieldDecorator } = this.props.form;
		const payClass = (this.state.value == 2) ? 'pay' : 'pay hide';

		let caOrgList = '';
		if(this.state.orgList.length !== 0){
			caOrgList = this.state.orgList.map((e,i)=>{
				return (<Option key={e.id} value={e.type}>{e.nameCn}</Option>)
			})
		}else {
			caOrgList = (<Option value="no data">no data</Option>)
		}
		return(	
			<div className="subTopBox">
				<div className="subTopBox-hd">
					<div className="hd-title">
						<span className="step active">
							<i>1</i>
						创建秘钥</span>
						<em className="line active"></em>
						<span className="step active">
							<i>2</i>
						创建证书</span>
						<em className="line"></em>
						<span className="step">
							<i>3</i>
						下载证书</span>
					</div>
				</div>
				<div className="createSuccess">
					<h3 className="partTitle">密钥生成成功！</h3>
					<FormItem
						    label="公钥"
						    labelCol={{ span: 5 }}
						    wrapperCol={{ span: 11 }}
						>	
							<Input disabled value={this.state.defaultValue} />
							<p className="classTips">您可以在“账户服务-密钥管理”中查看管理您创建的密钥</p>
							<p className="classTips noticeTips">提示：由于密钥已经生成成功，请勿刷新或退出该创建证书页面，否则，你需要重新开始创建证书流程，且需要重新创建一个全新的密钥。</p>
						</FormItem>
				</div>
				<div className="createKey createcertificate">
					<h3 className="partTitle">创建一个证书</h3>
					<Form onSubmit={this.handleSubmit}>
						<FormItem
						    label="证书ID"
						    labelCol={{ span: 5 }}
						    wrapperCol={{ span: 11 }}
						>	
							{getFieldDecorator('caId',{
								rules: [{required: true, message: '请输入您想创建的证书ID'}]
							})(
								<Input placeholder="请输入您想创建的证书ID" />
							)}
							<p className="classTips redColor">* 必填 只能使用英文字母、数字及字符“_”和“-”</p>
						</FormItem>
						<FormItem
							className="certificateType"
						    label="证书类型"
						    labelCol={{ span: 5 }}
						    wrapperCol={{ span: 11 }}
						>	
							<RadioGroup name="radiogroup" defaultValue={1} onChange={this.onChangeRadio} value={this.state.value}>
					          <Radio value={1}>默认证书</Radio>
					          <Radio value={2}>付费证书</Radio>
					        </RadioGroup>
					        <div className={payClass}>
					        	CA机构选择 
					        	<Select defaultValue="请选择证书" style={{ width: 120,marginLeft: 10 }} onChange={this.handleChange}>
					        		{caOrgList}
					        	</Select>
					        </div>
						</FormItem>
						<FormItem
							className="submitBtns"
						    label=" "
						    labelCol={{ span: 5 }}
						    wrapperCol={{ span: 11 }}
						>	
							<div>
								<Button type="primary" htmlType="submit" className="joinBtn">确认创建证书</Button>
							</div>
						</FormItem>
					</Form>
				</div>
			</div>	
			)
	}
}

const createCertificate = Form.create()(createcertificate);
export default connect((state) => {
    return { ...state };
  })(createCertificate);


